﻿using System.Windows.Forms;
using System.Data;
using System.Data.Common;

namespace PengSW.DbTools
{
    public partial class GeneralDataSourceEdit : UserControl
    {
        public GeneralDataSourceEdit()
        {
            InitializeComponent();

            m_Providers = DbProviderFactories.GetFactoryClasses();
            foreach (DataRow aDataRow in m_Providers.Rows)
            {
                cboDataProvider.Items.Add(aDataRow[2]);
            }

            Bind(m_GeneralDataSource);
        }

        public event System.EventHandler Change;

        public void Bind(GeneralDataSource aGeneralDataSource)
        {
            m_IsBinding = true;
            m_GeneralDataSource = aGeneralDataSource;
            cboDataProvider.Text = m_GeneralDataSource.DataProvider;
            txtConnectionString.Text = m_GeneralDataSource.ConnectionStringWithoutPassword;
            txtPassword.Text = m_GeneralDataSource.Password;
            m_IsBinding = false;
        }

        public string DataProvider { get { return cboDataProvider.Text.Trim(); } }
        public string ConnectionStringWithoutPassword { get { return txtConnectionString.Text.Trim(); } }
        public string Password { get { return txtPassword.Text; } }

        public bool ParametersIsReady
        {
            get
            {
                return DataProvider != string.Empty && ConnectionStringWithoutPassword != string.Empty;
            }
        }

        public void Accept()
        {
            m_GeneralDataSource.DataProvider = cboDataProvider.Text;
            m_GeneralDataSource.ConnectionStringWithoutPassword = txtConnectionString.Text;
            m_GeneralDataSource.Password = txtPassword.Text;
        }

        public GeneralDataSource CreateDataSource()
        {
            GeneralDataSource aDataSource = new GeneralDataSource();
            aDataSource.DataProvider = DataProvider;
            aDataSource.ConnectionStringWithoutPassword = ConnectionStringWithoutPassword;
            aDataSource.Password = Password;
            return aDataSource;
        }

        private DataTable m_Providers;
        private GeneralDataSource m_GeneralDataSource = new GeneralDataSource();

        private bool m_IsBinding = false;
        private void Content_OnChanged(object sender, System.EventArgs e)
        {
            if (m_IsBinding) return;
            if (Change != null) Change(sender, e);
        }
    }
}
